<template>
	<!-- 微信小程序 -->
	<!-- #ifdef MP-WEIXIN -->
	<view class="video-container">
		<view class="video-box">
			
			<!-- src="rtmp://ns8.indexforce.com/home/mystream" -->
			<!-- 直播 -->
			<live-player
				v-if="data.program.program_type==='1'"
				:id="data.id"
				:src="data.url"
				:autoplay="autoplay"
				class="video-player"
				mode="live" 
				:muted="true"
				:background-mute="true"
				:object-fit="videoOption.videoSize"
				@statechange="liveStateChange"
				@error="handleError"
				>
			</live-player>
			<!-- 回放 -->
			<video
				v-else-if="data.program.program_type==='2'"
				class="video-player"
				ref="videoRef"
				:id="data.id"
				:controls="false"
				:show-loading="false"
				:src="data.program.playback_url"
				:autoplay="autoplay"
				:loop="true"
				:object-fit="videoOption.videoSize"
				@click="togglePlay"
				@timeupdate="onTimeUpdate"
				@loadedmetadata="onLoadedMetadata"		
				@error="handleError"
				>
			</video>
			<!-- TODO 视频 -->
<!-- 			<video
				v-else-if="data.program.program_type==='2'"
				class="video-player"
				ref="videoRef"
				:id="data.id"
				:controls="false"
				:show-loading="false"
				:src="data.program.playback_url"
				:autoplay="props.autoplay"
				:loop="true"
				:object-fit="videoOption.videoSize"
				@click="togglePlay"
				@timeupdate="onTimeUpdate"
				@loadedmetadata="onLoadedMetadata"		
				@error="handleError"
				>
			</video> -->
			<!-- 播放按钮 -->
			<image class="icon--play" src="../../static/play.png" mode="aspectFit" v-if="!isPlaying" @click="togglePlay"></image>
			
			<!-- 显示视频信息 -->
			<section class="video-info">
				<!-- 头部部分，显示视频标题和类别 -->
				<header class="video-info__header">
					<section class="video-info__header-desc">
						<h2 class="video-info__header-desc-title">{{data.data_title}}</h2>
						<span class="video-info__header-desc-type">
							#{{data.detail.datas.live_type_name?data.detail.datas.live_type_name:"暂无"}}
						</span>
					</section>
					
					<div class="video-info__header-full" @click="onClickToDetails">完整视频</div>
				</header>
				
				<!-- 自定义进度条 -->
				<!-- video有controls属性：是否显示默认播放控件（播放/暂停按钮、播放进度、时间） -->
				<!-- v-if="data.state_id == '2' && data.state_id == '3'" -->
				<!-- backgroundColor="#fcb603" -->
				<slider
					:value="currentProgress"
					max="100"
					activeColor="#fc8403"
					block-size="12"
					block-color="orange"
					backgroundColor="rgba(#fff,.3)"
					@change="onSliderChange"
					@changing="onSliderChanging"
					class="video-slider"
				>
				</slider>
				
				<div class="video-info__details flex">
					<div class="video-info__author">
						<img 
							:src="data.detail.datas.club_logo?data.detail.datas.club_logo:'/static/user.png'" 
							alt="发布者头像" 
							class="video-info__author-avatar" />
						<span class="video-info__author-name">{{data.club_name}}</span>
					</div>
					
					<!-- 互动部分 -->
					<view class="video-info__interaction flex">
						<view class="video-info__interaction-item flex-column">
							<text class="video-info__interaction-text">{{data.clicked_num}}</text>
							<image src="/static/views--white.png" mode="aspectFill" class="video-info__interaction-icon"></image>
						</view>
						
						<view class="video-info__interaction-item flex-column">
							<text class="video-info__interaction-text">{{data.liked_num}}</text>
							<image src="/static/like--white.png" mode="aspectFill" class="video-info__interaction-icon"></image>
						</view>
						
						<view class="video-info__interaction-item flex-column">
							<text class="video-info__interaction-text">{{data.comment_num}}</text>
							<image src="/static/comment--white.png" mode="aspectFill" class="video-info__interaction-icon"></image>
						</view>
						
						<view class="video-info__interaction-item flex-column">
							<text class="video-info__interaction-text">{{data.subscribe_num}}</text>
							<image src="/static/subscribe--white.png" mode="aspectFill" class="video-info__interaction-icon"></image>
						</view>
						
						<view class="video-info__interaction-item flex-column">
							<text class="video-info__interaction-text">{{data.shared_num}}</text>
							<image src="/static/share--white.png" mode="aspectFill" class="video-info__interaction-icon"></image>
						</view>
					</view>
				</div>
				
			</section>
		</view>
	</view>
	<!-- #endif -->
	
	
	
	<!--  APP端 -->
	<!-- #ifdef APP -->
	<view class="video-container">
		<view class="video-box">
			
			<video
				v-if="data.program.program_type==='2'"
				class="video-player"
				ref="videoRef"
				:id="data.id"
				:src="data.program.playback_url" 
				:autoplay="autoplay"
				@error="handleError"
			  >
			</video>
			<!-- 播放按钮 -->
			<image class="icon--play" src="../../static/play.png" mode="aspectFit" v-show="!isPlaying" @click="videoPlay"></image>
			
			<!-- 显示视频信息 -->
			<section class="video-info">
				<!-- 头部部分，显示视频标题和类别 -->
				<header class="video-info__header">
					<section class="video-info__header-desc">
						<h2 class="video-info__header-desc-title">{{data.data_title}}</h2>
						<span class="video-info__header-desc-type">
							#{{data.detail.datas.live_type_name?data.detail.datas.live_type_name:"暂无"}}
						</span>
					</section>
					
					<div class="video-info__header-full" @click="onClickToDetails">完整视频</div>
				</header>
				
				
				<div class="video-info__details">
					<div class="video-info__author">
						<img 
							:src="data.detail.datas.club_logo?data.detail.datas.club_logo:'/static/user.png'" 
							alt="发布者头像" 
							class="video-info__author-avatar" />
						<span class="video-info__author-name">{{data.club_name}}</span>
					</div>
				</div>
				
			</section>
		</view>
	</view>
	<!-- #endif -->
</template>

<script setup>
import { ref, onMounted, watch,toRefs, getCurrentInstance, onUnmounted } from 'vue';
import { onHide, onShow } from '@dcloudio/uni-app';

// 参数说明
// videoSize 是 控制 video 的 object-fit 有 contian 和 cover 两个选项
const props = defineProps({
	currentIndex: Number,
	activeIndex: Number,
	autoplay: Boolean,
	is_rtmp: String,
	videoOption: Object,
	data: Object,
});

// 定义自定义事件
const emit = defineEmits(['video-error']);

// 判断视频是否在播放
const isPlaying = ref(true);
const currentTime = ref(0);
const duration = ref(0);
const currentProgress = ref(0);
const videoRef = ref(null);

// 是否初次拉流
let isFirst = true;
const onLoadedData = () => {
	// console.log('获取数据')
}

let videoContext;

// 是否第一次得到视频
let isFirstGetVideo = true;

// 控制视频播放的函数
const videoPlay = () => {
	// console.log('播放视频')
	if (videoContext) {
	    videoContext.play();
	    isPlaying.value = true;
	}
};

// 视频暂停
const videoPause = () => {
	// console.log('暂停视频')
	if (videoContext) {
	    videoContext.pause();
	    isPlaying.value = false;
	}
};

// 切换播放和暂停
const togglePlay = () => {
	if (isPlaying.value) {
		videoPause();
	} else {
		videoPlay();
	}
};

// 视频开始播放
const videoStartPlay = () => {
	// console.log('视频播放');
	// uni.hideLoading();
};

const videoWaiting = () => {
	// console.log('视频缓冲中');
};

// 监听视频时间变化的函数
const onTimeUpdate = (e) => {
	currentTime.value = e.detail.currentTime;
	duration.value = e.detail.duration;
	currentProgress.value = (currentTime.value / duration.value) * 100;
	if (currentTime.value === duration.value) {
		// console.log('end')
		// isPlaying.value=false
		videoPause();
	}
};

// 视频加载后获取视频信息的函数
const onLoadedMetadata = (e) => {
	duration.value = e.detail.duration;
	if (isFirstGetVideo) {
		// console.log('第一次获取到数据!')
		// 收起加载
		uni.hideLoading();
		isFirstGetVideo = false;
	}
};

const onSliderChange = (e) => {
	const seekTime = (e.detail.value / 100) * duration.value;
	// const videoContext = uni.createVideoContext(props.videoId);
	console.log('拉动了视频进度条,进度条的 e：', e)
	videoContext.seek(seekTime);
};

const onSliderChanging = (e) => {
	// console.log('视频进度条在改变,e：', e)
	currentProgress.value = e;
	currentTime.value = (e / 100) * duration.value;
};

const formatTime = (time) => {
	const minutes = Math.floor(time / 60);
	const seconds = Math.floor(time % 60);
	return `${minutes}:${seconds < 10? '0' : ''}${seconds}`;
};


// 处理视频报错函数
const handleError = (e) => {
	console.error('Video playback error:', e);
	// 将当前视频的 index 发给父组件
	// 父组件据此跳转到下一个视频
	emit('video-error', props.currentIndex);
	uni.showToast({
		title: '视频播放失败，请检查网络或稍后重试',
		icon: 'none'
	});
};

// 直播码变化检测函数
const liveStateChange = (e) => {
	console.log('live-player code:', e.detail.code);
	if (e.detail.code === 2001 && isFirst) {
		uni.showLoading({
			title: '加载中'
		});
	} else if (e.detail.code === 2004 && isFirst) {
		uni.hideLoading();
		isFirst = false;
	}
};


// 用来控制别的视频的开关
watch(() => props.activeIndex, (newVal, oldVal) => {
	if (newVal === props.currentIndex) {
		// console.log('当前播放的视频编号:', props.activeIndex);
		// console.log('当前播放的视频信息:', props.data);
		videoPlay();
	} else {
		videoPause();
	}
});


// 跳转到视频详情页
const onClickToDetails = () => {
	// TODO 这里分情况，1.跳转到直播，2.跳转到回放，3.跳转到视频
	// 只传 id，在对应的详情页中进行 get—detail
	// console.log('跳转前页面的数据：', props.data)
	const params = {
		id: props.data.data_id
	};
	// 直播中
	if (props.data.data_type == '直播' && props.data.detail.datas.is_rtmp == '1') {
		uni.navigateTo({
			url: `/pages/liveDetails/liveDetails?id=${params.id}`
		});
	}
	// 直播回放
	else if (props.data.data_type == '直播' && props.data.detail.datas.is_rtmp == '0') {
		uni.navigateTo({
			url: `/pages/liveDetails/liveDetails?id=${params.id}`
		});
	}
	// 视频
	else {
		uni.navigateTo({
			url: `/pages/videoDetails/videoDetails?id=${params.id}`
		});
	}


};

onMounted(() => {
	// console.log('单个视频数据：', props.data)
	// console.log('单个视频数据：', props.data.id)
	const instance = getCurrentInstance();
	// #ifdef MP-WEIXIN
	videoContext = uni.createVideoContext(props.data.id, instance.proxy);
	// #endif

	// #ifndef MP-WEIXIN
	videoContext = uni.createVideoContext(props.data.id);
	// #endif


	// if(videoContext){
	//  console.log('创建成功');
	// }


	// 用于去除没有设置自动播放产生的图标
	// isPlaying.value = false;
	// videoPlay();
	// isPlaying.value = true;
	// videoPlay();
	if(isFirstGetVideo.value){
		uni.showLoading({
			title: '视频数据加载中，请稍等'
		});
	}



});


onUnmounted(() => {
	// console.log('视频页面卸载!')
});


onShow(() => {
	// console.log('视频展示')
	if (props.activeIndex === props.currentIndex) {
		// console.log('当前播放的视频编号:', props.activeIndex);
		videoPlay();
	} else {
		videoPause();
	}
});


onHide(() => {
	// console.log('视频页面 Hide!')
	videoPause();
});


// 使用 defineExpose 正确的方式
defineExpose({
	handleError
});


</script>

<style lang="scss" scoped>
	.video-container{
		position: relative;
		width: 100%;
		height: 100%;
		background-color: #000;
		display: flex;
		flex-direction: column;
		align-items: center;
		/* justify-content: center; */
	}
	
	.video-box{
		position: relative;
		width: 100%;
		height: 100%;
/* 		height: 400rpx;
		margin-top: 400rpx; */
	}
	
	.video-player{
		width: 100%;
		height: 100%;
/* 		width: 500rpx;
		height: 500rpx; */
	}
	
	.uni-video-video{
		object-fit: cover;
	}
	
	.icon--play{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		width: 100rpx;
		height: 100rpx;
	}
	
	/* 进度条样式 */
	.video-slider{
		width: 95%;
		margin: 10rpx auto;
	}
	
	/* 显示视频信息样式 */
	.video-info{
		width: 100%;
		color: #fff;
		position: absolute;
		z-index: 10;
		bottom: 0;
		left: 0;
		
		&__header{
			margin-left: 10rpx;
			display:flex;
			justify-content: space-between;
			align-items: center;
			&-desc{
				&-title{
					font-size: 40rpx;
				}
				
				&-type{
					font-size: 40rpx;
				}
			}
			
			// 完整视频
			&-full{
				font-size: 32rpx;
				padding: .5em 1em;
				padding-left: 1.5em;
				background-color: rgba(255, 255, 255, .15);
				border-top-left-radius: 40rpx;
				border-bottom-left-radius: 40rpx;
				word-break: keep-all;
			}
		}
		
		&__details{
			width: 100%;
			height: 100rpx;
			box-sizing: border-box;
			padding: 0 20rpx;
			justify-content: space-between;
			background-color: rgba(255, 255, 255, .1);
		}
		
		// 发布者信息
		&__author{
			display: flex;
			align-items: center;
			margin-left: 10rpx;
			&-avatar{
				width: 50rpx;
				height: 50rpx;
				margin-right: 10rpx;
			}
		}
		
		// 互动部分
		&__interaction{
			&-item{
				margin-right: 47rpx;
				align-items: center;
				&:nth-last-child(1){
					margin-right: 0;
				}
			}
			&-icon{
				width: 33rpx;
				height: 33rpx;
			}
		}
	}
	
	@media screen and (min-width: 600px) {
		.video-info{
			&__header{
				&-desc{
					&-title{
						font-size: 4vw;
					}
					
					&-type{
						font-size: 4vw;
					}
				}
				
				// 完整视频
				&-full{
					font-size: 3.2vw;
				}
			}
			
			&__details{
				width: 100%;
				height: 100rpx;
				box-sizing: border-box;
				padding: 0 20rpx;
				justify-content: space-between;
				background-color: rgba(255, 255, 255, .1);
			}
			
			// 发布者信息
			&__author{
				display: flex;
				align-items: center;
				margin-left: 10rpx;
				&-avatar{
					width: 50rpx;
					height: 50rpx;
					margin-right: 10rpx;
				}
				&-name{
					font-size: 2.6vw;
				}
			}
			
			// 互动部分
			&__interaction{
				&-item{
					margin-right: 47rpx;
					align-items: center;
					&:nth-last-child(1){
						margin-right: 0;
					}
				}
				&-icon{
					width: 33rpx;
					height: 33rpx;
				}
				&-text{
					font-size: 2.5vw;
				}
			}
		}
	}
</style>